<template>
  <div class="note-editor">
    <div class="back-button-container">
      <el-button type="text" @click="$emit('close')" class="back-button">
        <el-icon><ArrowLeft /></el-icon>
        返回
      </el-button>
    </div>

    <div class="editor-header">
      <div class="header-row">
        <!-- 标题输入框 -->
        <el-input
          v-model="note.title"
          placeholder="输入标题"
          class="title-input"
          clearable
          :readonly="isReadOnly"
          :disabled="isReadOnly"
        />

        <!-- 话题输入框 -->
        <el-autocomplete
          v-model="note.topic"
          :fetch-suggestions="queryTopics"
          placeholder="输入话题标签(可选)"
          class="topic-input"
          clearable
          :readonly="isReadOnly"
          :disabled="isReadOnly"
        />

        <div class="public-container" v-if="!isReadOnly">
          <el-switch
            v-model="note.is_public"
            class="public-switch"
            active-text="公开"
            inactive-text="私密"
          />
        </div>
        <div class="public-container" v-else>
          <el-tag :type="note.is_public ? 'success' : 'info'">
            {{ note.is_public ? '公开' : '私密' }}
          </el-tag>
        </div>
      </div>
    </div>

    <div class="tinymce-container">
      <Editor
        v-if="!isReadOnly"
        :init="editorConfig"
        v-model="note.content"
      />
      <div v-else class="content-readonly" v-html="note.content"></div>
    </div>

    <div class="action-buttons" v-if="!isReadOnly">
      <el-button type="primary" @click="saveNote" :loading="submitting">
        保存笔记
      </el-button>
    </div>
  </div>
</template>

<script setup>
import 'tinymce'
import { ref, reactive, onMounted, computed } from 'vue'
import Editor from '@tinymce/tinymce-vue'
import { ElMessage } from 'element-plus'
import { ArrowLeft } from '@element-plus/icons-vue'
import axios from 'axios'

const props = defineProps({
  noteId: {
    type: [String, Number],
    default: null
  },
  userInfo: {
    type: Object,
    required: true
  }
})

const emit = defineEmits(['close'])

const note = reactive({
  title: '',
  content: '',
  topic: '',
  is_public: false,
  user: null // 存储笔记作者ID
})

const submitting = ref(false)


// 判断是否为只读模式：当前用户不是笔记作者时为只读
const isReadOnly = computed(() => {
  return note.user !== props.userInfo.id
})

// TinyMCE编辑器配置
const editorConfig = {
  base_url: '/tinymce',  // 指定本地资源路径
  suffix: '.min',        // 使用压缩版本
  height: 400,
  menubar: true,
  plugins: [
    'advlist', 'autolink', 'lists', 'link', 'charmap', 'preview',
    'anchor', 'searchreplace', 'visualblocks', 'code', 'fullscreen',
    'insertdatetime', 'media', 'table', 'code', 'help', 'wordcount'
  ],
  toolbar: 'undo redo | formatselect | bold italic backcolor | ' +
    'alignleft aligncenter alignright alignjustify | bullist numlist ' +
    'outdent indent | removeformat | help | code',
  language_url: '/tinymce/langs/zh_CN.js',  // 指定语言包路径
  language: 'zh_CN',
  skin: 'oxide',
  skin_url: '/tinymce/skins/ui/oxide',  // 指定皮肤路径
  content_css: '/tinymce/skins/content/default/content.css'  // 指定内容样式路径
}


// 话题搜索建议
const queryTopics = async (queryString, callback) => {
  if (!queryString || isReadOnly.value) {
    callback([])
    return
  }

  try {
    const response = await axios.get(`/backend/api/note/search/topics/?q=${queryString}`)
    const suggestions = response.data.topics.map(topic => ({
      value: topic
    }))
    callback(suggestions)
  } catch (error) {
    console.error('搜索话题失败:', error)
    callback([])
  }
}

// 保存笔记
const saveNote = async () => {
  if (isReadOnly.value) {
    ElMessage.error('无权限编辑此笔记')
    return
  }

  if (!note.content.trim()) {
    ElMessage.warning('请输入笔记内容')
    return
  }

  submitting.value = true

  try {
    const noteData = {
      title: note.title,
      content: note.content,
      topic: note.topic,
      is_public: note.is_public,
      user: props.userInfo.id
    }

    let response;

    if (props.noteId) {
      // 更新笔记
      response = await axios.put(`/backend/api/note/update/${props.noteId}/`, noteData)
      if (response.status === 200) {
        await axios.put(`/backend/api/note/publish/${props.noteId}/`, {
          is_public: note.is_public
        })
      }
    } else {
      // 创建新笔记
      response = await axios.post('/backend/api/note/create/', noteData)
    }

    console.log('保存笔记响应:', response)
    ElMessage.success(props.noteId ? '笔记更新成功' : '笔记创建成功')
    emit('close')
  } catch (error) {
    console.error('保存笔记失败:', error)
    if (error.response) {
      switch (error.response.status) {
        case 403:
          ElMessage.error('没有权限执行此操作')
          break
        case 404:
          ElMessage.error(props.noteId ? '笔记不存在' : '创建笔记失败')
          break
        case 400:
          ElMessage.error(error.response.data.message || '请求参数错误')
          break
        default:
          ElMessage.error('保存失败，请稍后重试')
      }
    } else {
      ElMessage.error('网络错误,请检查网络连接')
    }
  } finally {
    submitting.value = false
  }
}

// 获取笔记详情
const fetchNoteDetail = async () => {
  if (!props.noteId) return

  try {
    const response = await axios.get(`/backend/api/note/detail/${props.noteId}/`)
    if (response.data) {
      note.title = response.data.title
      note.content = response.data.content
      note.topic = response.data.topic || ''
      note.is_public = response.data.is_public
      note.user = response.data.user // 设置笔记作者ID
    }
  } catch (error) {
    console.error('获取笔记详情失败:', error)
    if (error.response && error.response.status === 404) {
      ElMessage.error('笔记不存在')
    } else {
      ElMessage.error('获取笔记详情失败')
    }
    emit('close')
  }
}

onMounted(() => {
  if (props.noteId) {
    fetchNoteDetail()
  } else {
    // 新建笔记时设置当前用户为作者
    note.user = props.userInfo.id
  }
})
</script>

<style scoped>
.note-editor {
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.back-button-container {
  margin-bottom: 16px;
}

.back-button {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #606266;
}

.back-button:hover {
  color: #409EFF;
}

.back-button .el-icon {
  margin-right: 4px;
}

.editor-header {
  margin-bottom: 16px;
  border-bottom: 1px solid #eee;
  padding-bottom: 16px;
}

.header-row {
  display: flex;
  align-items: center;
  gap: 12px;
}

.title-input {
  width: 200px !important;
  margin-right: 12px;
}

.topic-input {
  width: 200px !important;
}

.public-container {
  margin-left: auto;
  display: flex;
  align-items: center;
}

.public-switch {
  flex-shrink: 0;
}

.tinymce-container {
  margin-bottom: 20px;
}

.content-readonly {
  min-height: 400px;
  padding: 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background-color: #f8f9fa;
  overflow-y: auto;
}

.action-buttons {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}

:deep(.tox-tinymce) {
  border-radius: 4px;
}

:deep(.tox .tox-toolbar__primary) {
  background: none;
}

:deep(.el-input__wrapper) {
  width: 300px;
}

:deep(.el-autocomplete) {
  width: auto;
}

:deep(.el-input__wrapper),
:deep(.el-autocomplete .el-input__wrapper) {
  border-radius: 4px;
  box-shadow: 0 0 0 1px #dcdfe6 inset;
}

:deep(.el-input.is-disabled .el-input__wrapper) {
  background-color: #f8f9fa;
  color: #606266;
}
</style>